package com.daocao.hua.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.daocao.hua.R;
import com.daocao.hua.api.Api;
import com.daocao.hua.api.bean.IdCardIndentityBean;
import com.daocao.hua.api.bean.UploadImageBean;
import com.daocao.hua.api.bean.UploadSubmitIdcardBean;
import com.daocao.hua.constant.Const;
import com.daocao.hua.constant.IdCardBitmap;
import com.daocao.hua.model.CertificationBasicsModel;
import com.daocao.hua.model.DealBeforeV3Model;
import com.daocao.hua.util.GlideRoundTransform;
import com.daocao.hua.util.IdentityStepUtil;
import com.daocao.hua.util.ImageUtil;
import com.daocao.hua.util.Network;
import com.daocao.hua.util.RxLifeUtil;
import com.daocao.hua.util.ToastUtil;
import com.daocao.hua.util.UI;
import com.daocao.hua.view.Dialog;
import com.daocao.hua.view.FlowViewHorizontal;
import com.daocao.hua.view.MyHorizontalScrollView;
import com.daocao.hua.view.V19FrameLayout;
import com.daocao.hua.view.uploadImage.UploadImgAdapter;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/6/10.
 */

public class V3IdcardIdentityActivity extends BaseActivity {
    @BindView(R.id.img_front)
    ImageView imgFront;
    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.img_people)
    ImageView imgPeople;
    @BindView(R.id.edit_idcard_name)
    EditText editIdcardName;
    @BindView(R.id.edit_idcard_num)
    EditText editIdcardNum;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    Unbinder unbinder;
    @BindView(R.id.scrollView)
    MyHorizontalScrollView scrollView;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.btn_change)
    TextView btnChange;
    @BindView(R.id.step_view)
    FlowViewHorizontal stepView;
    private UploadImgAdapter uploadImgAdapter;
    private boolean isFirstGo = true;
    private boolean isOneReady = false;
    private boolean isTwoReady = false;
    private int takeType;
    private static final String DEFAULT_NAME1 = "front_image.jpg";
    private static final String DEFAULT_NAME2 = "back_image.jpg";
    private static final String DEFAULT_NAME3 = "people_image.jpg";
    private boolean frontIdentity;
    private boolean backIdentity;
    private UploadSubmitIdcardBean newModel = new UploadSubmitIdcardBean();
    private GlideRoundTransform glideRoundTransform;
    private ArrayList<CertificationBasicsModel.DataBean> oneKeyData;
    private ArrayList<DealBeforeV3Model.DataBean.UplistsBean> SomeKeyData;
    private IdentityStepUtil stepUtil;
    private String bizType = "realname";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_idcard_identity_v3);
        initBar();
        unbinder = ButterKnife.bind(this);
        init();
    }

    private void init() {
        txtTitle.setText("身份认证");
        glideRoundTransform = new GlideRoundTransform(this, 5);
        glideRoundTransform.setExceptCorner(false, false, true, true);
        oneKeyData = getIntent().getParcelableArrayListExtra(Const.KEY.ONE_KEY);
        SomeKeyData = getIntent().getParcelableArrayListExtra(Const.KEY.SOME_IDENTITY_KEY);
        stepUtil = new IdentityStepUtil(this);
        stepUtil.setIdentityData(bizType, txtTitle, stepView, oneKeyData, SomeKeyData);
    }

    /**
     * 上传身份证
     *
     * @param paramInt
     */
    private void getIdentity(int paramInt) {
        String str = "";
        if (paramInt == 0) {
//            正面
            str = ImageUtil.Bitmap2StrByBase64(IdCardBitmap.bitmap);
        } else if (paramInt == 1) {
//            反面
            str = ImageUtil.Bitmap2StrByBase64(IdCardBitmap.bitmap);
        }
        getIdentityInfo(paramInt, str);
    }

    public void getIdentityInfo(int paramInt, String paramString) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        IdCardIndentityBean bean = new IdCardIndentityBean();
        bean.img = paramString;
        Api.api_service.getIdentityInfo(paramInt, bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(item -> {
                    if (item.getStatus() != 0) {
                        if (paramInt == 0) {
//       正面
                            if (TextUtils.isEmpty(item.getName()) || TextUtils.isEmpty(item.getGendor()) || TextUtils.isEmpty(item.getNation()) || TextUtils.isEmpty(item.getBirthday()) || TextUtils.isEmpty(item.getAddress()) || TextUtils.isEmpty(item.getIdno()) || TextUtils.isEmpty(item.getFront_image())) {
                                ToastUtil.makeText(this, getResources().getString(R.string.not_discern_front), Toast.LENGTH_SHORT).show();
                                frontIdentity = false;
                                return;
                            }
                            frontIdentity = true;
                            newModel.setName(item.getName());
                            newModel.setFront_image(item.getFront_image());
                            newModel.setIdno(item.getIdno());
                            newModel.setBirthday(item.getBirthday());
                            newModel.setGendor(item.getGendor());
                            newModel.setAddress(item.getAddress());
                            newModel.setNation(item.getNation());
//                            imgFront.setImageBitmap(IdCardBitmap.bitmap);
                            editIdcardName.setText(item.getName());
                            editIdcardNum.setText(item.getIdno());
                            Glide.with(this).load(item.front_image).transform(glideRoundTransform).into(imgFront);
                            if (frontIdentity && backIdentity && !TextUtils.isEmpty(newModel.getHand_image())) {
                                btnSubmit.setSelected(true);
                            }
                        } else {
                            if (TextUtils.isEmpty(item.getIssue_by()) || TextUtils.isEmpty(item.getValid_start()) || TextUtils.isEmpty(item.getValid_end()) || TextUtils.isEmpty(item.getBack_image())) {
                                ToastUtil.makeText(this, getResources().getString(R.string.not_discern_back), Toast.LENGTH_SHORT).show();
                                backIdentity = false;
                                return;
                            }
                            newModel.setValid_start(item.getValid_start());
                            newModel.setValid_end(item.getValid_end());
                            newModel.setBack_image(item.getBack_image());
                            newModel.setIssue_by(item.getIssue_by());
                            backIdentity = true;
                            Glide.with(this).load(item.back_image).transform(glideRoundTransform).into(imgBack);
                            if (frontIdentity && backIdentity && !TextUtils.isEmpty(newModel.getHand_image())) {
                                btnSubmit.setSelected(true);
                            }
//                            imgBack.setImageBitmap(IdCardBitmap.bitmap);
                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (IdCardBitmap.bitmap != null) {
            IdCardBitmap.bitmap.recycle();
            IdCardBitmap.bitmap = null;
        }
        stepUtil = null;
        unbinder.unbind();
        unbinder = null;
    }

    public void getSubmitidCard(UploadSubmitIdcardBean item) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        Api.api_service.getSubmitidCard(item).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
//                    fsdf
                    ToastUtil.makeText(this, "认证成功");
                    stepUtil.goToNext();
                });
    }

    public void uploadImg(Bitmap img) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();

        UploadImageBean bean = new UploadImageBean();
        bean.img = ImageUtil.Bitmap2StrByBase64(img, 100);
        Api.api_service.uploadImg(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    newModel.setHand_image(result.getUrl());
                    Glide.with(this).load(result.getUrl()).transform(glideRoundTransform).into(imgPeople);
                    if (frontIdentity && backIdentity && !TextUtils.isEmpty(newModel.getHand_image())) {
                        btnSubmit.setSelected(true);
                    }
                });
    }

    private void goToTakePhoto() {
        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                if (uploadImgAdapter == null) {
                    initUploadImgAdapter();
                }
                uploadImgAdapter.withMode(UploadImgAdapter.MODE_IMG).showDialog();
            }

            @Override
            public void superReject() {

            }
        }, R.string.camera_storage_card_p, R.string.get_cammra, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    private void initUploadImgAdapter() {
        uploadImgAdapter = new UploadImgAdapter(this, new UploadImgAdapter.Action2() {
            @Override
            public void call(Bitmap file, int mode) {
                if (mode == UploadImgAdapter.MODE_IMG) {
                    uploadImg(file);
                }
            }
        });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (resultCode == -1) {
                try {

                    if (takeType == 1) {
                        if (IdCardBitmap.bitmap != null) {
//                            fragmentOne.setPhoto(takeType, IdCardBitmap.bitmap);
                            getIdentity(0);
                        }
                    } else if (takeType == 2) {

                        if (IdCardBitmap.bitmap != null) {
//                            fragmentOne.setPhoto(takeType, IdCardBitmap.bitmap);
                            getIdentity(1);
                        }
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            if (uploadImgAdapter != null) {
                uploadImgAdapter.onActivityResult(requestCode, resultCode, data);
            }
        }

    }

    private void startActivity(String paramString) {
        Intent localIntent = new Intent(this, CameraActivity.class);
        localIntent.putExtra("path", "/sdcard/pictures");
        localIntent.putExtra("name", paramString);
        localIntent.putExtra("type", "idcard");
        startActivityForResult(localIntent, 100);
    }

    public void startTakePhoto(int type) {
        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                takeType = type;
                if (type == 1) {
                    startActivity(DEFAULT_NAME1);
                } else if (type == 2) {
                    startActivity(DEFAULT_NAME2);
                } else if (type == 3) {
                    goToTakePhoto();
                }
            }

            @Override
            public void superReject() {

            }
        }, R.string.camera_storage_card_p, R.string.get_cammra, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    private void showDialog() {
        Dialog.showV3DefaultDialog(this, "提示", "认证还未完成\n您确定要退出吗？", "取消", "确定", new Dialog.DialogDefaultClickListener() {
            @Override
            public void confirm() {
                finish();
            }

            @Override
            public void cancel() {

            }
        });
    }

    @Override
    public void onBackPressed() {
        showDialog();
    }

    @OnClick({R.id.btn_back, R.id.img_front, R.id.img_back, R.id.img_people, R.id.btn_submit, R.id.btn_change})
    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_change:
                editIdcardName.setEnabled(true);
                editIdcardName.requestFocus();
                InputMethodManager imm = (InputMethodManager) editIdcardName.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
                break;
            case R.id.btn_back:
                showDialog();
                break;
            case R.id.img_front:
                startTakePhoto(1);
                break;
            case R.id.img_back:
                startTakePhoto(2);
                break;
            case R.id.img_people:
                if (isFirstGo) {
                    isFirstGo = false;
                    Dialog.showIdcardImageDialog(this, "示例", new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {
                            startTakePhoto(3);
                        }

                        @Override
                        public void cancel() {

                        }
                    });
                } else {
                    startTakePhoto(3);
                }

                break;
            case R.id.btn_submit:
                if (!frontIdentity) {
                    Dialog.showV3DefaultDialog(this, "提示", "请添加身份证正面", "取消", "确定", new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {
                            startTakePhoto(1);
                        }

                        @Override
                        public void cancel() {

                        }
                    });
                    return;
                }
                if (!backIdentity) {
                    Dialog.showV3DefaultDialog(this, "提示", "请添加身份证反面", "取消", "确定", new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {
                            startTakePhoto(2);
                        }

                        @Override
                        public void cancel() {

                        }
                    });
                    return;
                }
                if (TextUtils.isEmpty(newModel.getHand_image())) {
                    Dialog.showV3DefaultDialog(this, "提示", "请添加手持身份证", "取消", "确定", new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {
                            startTakePhoto(3);
                        }

                        @Override
                        public void cancel() {

                        }
                    });
                    return;
                }
                if (UI.toString(editIdcardName).length() < 2) {
                    ToastUtil.makeText(this, "姓名请补充完毕");
                    return;
                }
                newModel.setName(UI.toString(editIdcardName));
                getSubmitidCard(newModel);
//                idcardSubmitBean.realname = UI.toString(editIdcardName);
//                getSubmitIdcard();
                break;
        }
    }
}
